<template>
  <div class="create-post">
    <h2 class="title is-3">{{ queryId ? '编辑文章' : '新建文章' }}</h2>
    <Uploader
      class="d-flex align-items-center justify-content-center bg-light"
      action="/apixyz/upload"
      :beforeUpload="uploadCheck"
      :resetfileStatus="resetfileStatus"
      @fileUploaded="onFileUpload"
      @fileUploadedError="onFileUploadError"
    >
      <h2>点击上传头图</h2>
      <template #loading>
        <div class="d-flex">
          <div class="spinner-border text-primary" role="status"></div>
          <h2>正在上传</h2>
        </div>
      </template>
      <template #uploaded="dataProps">
        <img :src="dataProps.uploadedData.data.url" />
        <button class="mx-2 btn btn-primary" @click.stop="deleteUpload">删除图片</button>
        <button class="mx-2 btn btn-primary">重新上传</button>
      </template>
    </Uploader>
    <ValidateForm @form-submit="handleFormSubmit">
      <ValidateInput v-model="titleVal" placeholder="请输入文章标题">
        <label class="label">文章标题：</label>
      </ValidateInput>
      <ValidateInput v-model="categoryVal" tag="select" :options="options" placeholder="请选择分类">
        <label class="label">文章分类：</label>
      </ValidateInput>
      <ValidateInput v-model="detail" tag="textarea" placeholder="请输入文章详情" rows="10">
        <label class="label">文章详情：</label>
      </ValidateInput>
      <template #submit="">
        <button class="btn btn-primary is-danger">{{ queryId ? '编辑文章' : '创建文章' }}</button>
      </template>
    </ValidateForm>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, ref, reactive, onMounted } from 'vue';
import ValidateInput from '@/components/Form/ValidateInput.vue';
import ValidateForm from '@/components/Form/ValidateForm.vue';
import Uploader from '@/components/Uploader.vue';
import { useStore } from 'vuex';
import { useRouter, useRoute } from 'vue-router';
import { GlobalDataProps } from '@/store/index';
import { PostProps, ResponseType, ImageProps } from '@/store/types';
import createMessage from '@/components/createMessage';
import axios from 'axios';
import { beforeUploadCheck } from '../common/utils';
export default defineComponent({
  name: 'create-post',
  components: { ValidateInput, ValidateForm, Uploader },
  setup() {
    const titleVal = ref<string>('');
    const categoryVal = ref<string>('');
    const detail = ref<string>('');
    const resetfileStatus = ref<string>('');
    const options = reactive(computed(() => store.getters.getOptions()));
    const store = useStore<GlobalDataProps>();
    const router = useRouter();
    const route = useRoute();
    const queryId = route.query.id;
    let imageId = '';
    // 获取接口数据
    onMounted(() => {
      store.dispatch('fetchColumns');
      if (queryId) {
        store.dispatch('fetchArticleDetail', queryId).then(rawDetail => {
          titleVal.value = rawDetail.data.title;
          categoryVal.value = rawDetail.data.cid;
          detail.value = rawDetail.data.content;
        });
      }
    });
    const handleFormSubmit = (val: boolean) => {
      if (val) {
        if (categoryVal.value && titleVal.value && detail.value) {
          const newPost: PostProps = {
            title: titleVal.value,
            content: detail.value,
            cid: categoryVal.value
          };
          if (!queryId) {
            // 使用actions异步提交, queryId不存在新建
            store.dispatch('createPost', newPost).then(() => {
              createMessage('发布成功', 'success', 2000);
              router.push({ name: 'column', params: { cid: newPost.cid } });
            });
          } else {
            // queryId存在编辑
            store.dispatch('fetchEditArticle', { id: queryId, updateObj: newPost }).then(() => {
              createMessage('编辑成功', 'success', 2000);
              router.push({ name: 'column', params: { cid: newPost.cid } });
            });
          }
        } else {
          createMessage('请输入完整信息', 'error', 2000);
        }
        console.log(imageId, 'imageId');
        // if (imageId) {
        //   newPost.image = imageId;
        // }

        // 使用mutation同步提交
        /* store.commit('createPost', newPost);
          router.push({
            name: 'column',
            params: { id: columnId }
          }); */
      }
    };
    const handleFormInput = (e: Event) => {
      const target = e.target as HTMLInputElement;
      const files = target.files;
      if (files) {
        const uploadFile = files[0];
        const formData = new FormData();
        formData.append(uploadFile.name, uploadFile);
        axios
          .post('/apixyz/upload', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          })
          .then(res => {
            console.log(res);
          });
      }
    };
    const beforeUpload = (file: File) => {
      const isJPG = file.type === 'image/jpeg';
      if (!isJPG) {
        createMessage('上传的文件不是jpg格式', 'error');
      }
      return isJPG;
    };
    const uploadCheck = (file: File) => {
      const res = beforeUploadCheck(file, { format: ['image/jpeg', 'image/png'], size: 1 });
      const { error, passed } = res;
      if (error === 'size') {
        createMessage('上传的文件过大', 'error');
      }
      if (error === 'format') {
        createMessage('上传的文件格式不对', 'error');
      }
      return passed;
    };
    const onFileUpload = (rawData: ResponseType<ImageProps>) => {
      console.log(rawData.data._id, 'image......');
      if (rawData.data._id) {
        imageId = rawData.data._id;
      }
      resetfileStatus.value = '';
      createMessage(`上传图片ID ${rawData.data._id}`, 'success');
    };
    const onFileUploadError = (error: ResponseType<null>) => {
      resetfileStatus.value = '';
      createMessage(`图片上传失败 ${error.error}`, 'error');
    };
    const deleteUpload = () => {
      // 通过modal框点击二次确认
      resetfileStatus.value = 'ready';
    };
    return {
      titleVal,
      detail,
      resetfileStatus,
      categoryVal,
      options,
      queryId,
      handleFormInput,
      handleFormSubmit,
      beforeUpload,
      uploadCheck,
      onFileUpload,
      onFileUploadError,
      deleteUpload
    };
  }
});
</script>

<style lang="less">
.file-upload-container {
  height: 280px;
  cursor: pointer;
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}
</style>
